import 'package:cached_network_image/cached_network_image.dart';
import 'package:cave_flutter/network/whl_network_utils.dart';
import 'package:cave_flutter/utils/whl_user_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_preview/image_preview.dart';
import '../brick.dart';
import 'basic_widget.dart';

class UIImage extends UIContainer {
  //快捷属性
  final Image? image;
  final String? assetImage;
  final String? httpImage;
  final double? aspectRatio;
  final BoxFit? fit;
  final String? package;
  final Color? imageColor;
  final String? assetPlaceHolder;
  final Rect? centerSlice;
  //  大图
  final bool? disabledHttpBigImage;

  const UIImage({
    super.key,
    this.disabledHttpBigImage = false,
    //自身快捷属性
    this.image,
    this.assetImage,
    this.httpImage,
    this.aspectRatio,
    this.fit,
    this.package,
    this.imageColor,
    this.assetPlaceHolder,
    this.centerSlice,
    //快捷属性
    super.radius = 0,
    super.topLeftRadius,
    super.topRightRadius,
    super.bottomRightRadius,
    super.bottomLeftRadius,
    super.solidColor = Colors.transparent,
    super.strokeColor = Colors.transparent,
    super.strokeWidth,
    super.gradientStartColor,
    super.gradientEndColor,
    super.gradientBegin = Alignment.centerLeft,
    super.gradientEnd = Alignment.centerRight,
    //Container
    super.margin,
    super.padding,
    super.color,
    super.decoration,
    super.width,
    super.height,
    super.constraints,
    super.alignment,
    super.foregroundDecoration,
    super.transform,
    super.transformAlignment,
    super.clipBehavior = Clip.none,
    //GestureDetector
    super.onTapDown,
    super.onTapUp,
    super.onTap,
    super.onTapCancel,
    super.onLongPress,
    super.onLongPressEnd,
    super.onLongPressMoveUpdate,
  });

  @override
  Widget buildRealChild({List<Widget>? supportChildList}) {
    List<Widget> supportChildListTemp = supportChildList ?? [];
    if (supportChildListTemp.isNotEmpty) throw UnsupportedError("不支持重写");
    Widget? defaultImage;
    if (null == image) {
      //Asset类型
      String assetImageTemp = assetImage ?? "";
      //Http类型
      String httpImageTemp = httpImage ?? "";

      if (httpImageTemp.isNotEmpty && !httpImageTemp.startsWith("http")) {
        assetImageTemp = httpImageTemp;
      }

      if (assetImageTemp.isNotEmpty) {
        defaultImage = _renderAssetImage(assetImageTemp);
      } else if (httpImageTemp.isNotEmpty) {
        defaultImage = _renderUrlImage(httpImageTemp);
      } else {
        defaultImage =
            SizedBox(width: width, height: height, child: _renderErrorImage());
      }
    }

    // final String? assetImage;
    // final String? httpImage;
    Widget imageChild = image ?? (defaultImage ?? const UIEmptyWidget());
    Widget aspectRatioImage = (null == aspectRatio)
        ? imageChild
        : AspectRatio(aspectRatio: aspectRatio ?? 1, child: imageChild);
    String? bigImgUrl;
    if (disabledHttpBigImage != true &&
        httpImage != null &&
        httpImage!.isNotEmpty) {
      bigImgUrl = httpImage;
    }
    Widget realChild = bigImgUrl == null
        ? aspectRatioImage
        : _OpenImage(
            onTap: onTap,
            imgUrl: bigImgUrl,
            child: aspectRatioImage,
          );

    return super.buildRealChild(supportChildList: [realChild]);
  }

  ///UrlImage
  Widget _renderUrlImage(String urlImage) {
    return CachedNetworkImage(
      imageUrl: urlImage,
      // httpHeaders: {"Authorization":WhlNetWorkUtils.getAccessToken()},
      placeholderFadeInDuration: const Duration(seconds: 0),
      fadeInDuration: Duration.zero,
      fadeOutDuration: Duration.zero,
      width: width,
      height: height,
      placeholder: (BuildContext context, String url) {
        return ClipRRect(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(topLeftRadius ?? radius),
            topRight: Radius.circular(topRightRadius ?? radius),
            bottomRight: Radius.circular(bottomRightRadius ?? radius),
            bottomLeft: Radius.circular(bottomLeftRadius ?? radius),
          ),
          child: _renderPlaceHolderImage(),
        );
      },
      errorWidget: (BuildContext context, String url, dynamic error) {
        return ClipRRect(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(topLeftRadius ?? radius),
            topRight: Radius.circular(topRightRadius ?? radius),
            bottomRight: Radius.circular(bottomRightRadius ?? radius),
            bottomLeft: Radius.circular(bottomLeftRadius ?? radius),
          ),
          child: _renderErrorImage(),
        );
      },
      fit: fit,
      imageBuilder: (BuildContext context, ImageProvider imageProvider) {
        return ClipRRect(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(topLeftRadius ?? radius),
            topRight: Radius.circular(topRightRadius ?? radius),
            bottomRight: Radius.circular(bottomRightRadius ?? radius),
            bottomLeft: Radius.circular(bottomLeftRadius ?? radius),
          ),
          child: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: imageProvider,
                fit: fit,
              ),
            ),
          ),
        );
      },
    );
  }

  ///AssetImage
  Widget _renderAssetImage(String assetImage) {
    if (!assetImage.endsWith(".png") &&
        !assetImage.endsWith(".jpg") &&
        !assetImage.endsWith(".gif")) {
      assetImage = "$assetImage.png";
    }
    return ClipRRect(
      borderRadius: BorderRadius.only(
        topLeft: Radius.circular(topLeftRadius ?? radius),
        topRight: Radius.circular(topRightRadius ?? radius),
        bottomRight: Radius.circular(bottomRightRadius ?? radius),
        bottomLeft: Radius.circular(bottomLeftRadius ?? radius),
      ),
      child: Image.asset(
        'assets/images/$assetImage',
        width: width,
        height: height,
        package: package ?? WhlBrickKit().getAssetImagePath(),
        fit: fit,
        color: imageColor,
        centerSlice: centerSlice,
      ),
    );
  }

  ///PlaceHolderImage
  Widget _renderPlaceHolderImage() {
    String assetPlaceHolderTemp = assetPlaceHolder ?? "";
    if (assetPlaceHolderTemp.isNotEmpty) {
      return _renderAssetImage(assetPlaceHolderTemp);
    } else {
      return const Icon(
        Icons.downloading,
        color: Color(0xFFE2C4C4),
      );
    }
  }

  ///ErrorImage
  Widget _renderErrorImage() {
    String assetPlaceHolderTemp = assetPlaceHolder ?? "";
    if (assetPlaceHolderTemp.isNotEmpty) {
      return _renderAssetImage(assetPlaceHolderTemp);
    } else {
      return const Icon(
        Icons.error,
        color: Color(0xFFE2C4C4),
      );
    }
  }
}

class _OpenImage extends StatefulWidget {
  final Widget child;
  final String imgUrl;
  final String? imgOriginalUrl;
  final GestureTapCallback? onTap;
  const _OpenImage({
    super.key,
    required this.child,
    required this.imgUrl,
    this.onTap,
    this.imgOriginalUrl,
  });

  @override
  State<_OpenImage> createState() => __OpenImageState();
}

class __OpenImageState extends State<_OpenImage> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: widget.child,
      onTap: () {
        if (widget.onTap != null) {
          widget.onTap!();
        }
        if (widget.imgUrl.isNotEmpty) {
          openImagePage(
            Navigator.of(context),
            imgUrl: widget.imgUrl,
            imgOriginalUrl: widget.imgOriginalUrl,
          );
        }
      },
    );
  }
}
